<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">图书管理系统登录</h2>
      <el-form :model="form" @submit.prevent="onLogin" label-width="60px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin" style="width:100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const form = reactive({ username: '', password: '' })

const onLogin = async () => {
  try {
    const res = await axios.post('/api/auth/login', form)
    localStorage.setItem('token', res.data.token)
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + res.data.token
    ElMessage.success('登录成功')
    router.push('/borrower')
  } catch (e) {
    ElMessage.error('用户名或密码错误')
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f6fa;
}
.login-card {
  width: 420px;
  max-width: 90vw;
  padding: 30px 20px 10px 20px;
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
  font-weight: bold;
  font-size: 22px;
  letter-spacing: 2px;
}
.el-input {
  width: 100%;
}
</style> 